import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * author: MaHX
 * date: 2019/9/23/23:32
 * description:
 **/
public class TestForkJoin {
    public static void main(String args[]) {
        Instant start = Instant.now();
        ForkJoinPool forkJoinPool = new ForkJoinPool();

        ForkJoinTask<Long> task = new ForkJoinDemo(0,100000000L);

        Long sum = forkJoinPool.invoke(task);

        Instant end = Instant.now();

        System.out.println(sum);
        System.out.println("消耗时间："+Duration.between(start,end).toMillis());

    }
//    @Test
//    public void test1(){
//        long sum = 0L;
//        for (long i = 0L; i < 10000000L; i++) {
//            sum += i;
//        }
//        System.out.println(sum);
//    }

    static class ForkJoinDemo extends RecursiveTask<Long> {
        private long start;
        private long end;

        private static final long THURSHOLD = 1000L;

        public ForkJoinDemo(long start, long end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Long compute() {
            long length = end - start;
            long sum = 0L;
            if (length <= THURSHOLD) {
                for (long i = start; i <= end; i++) {
                    sum += i;
                }
                return sum;
            } else {
                long middle = (start + end) / 2;
                ForkJoinDemo left = new ForkJoinDemo(start, middle);
                left.fork();
                ForkJoinDemo right = new ForkJoinDemo(middle + 1, end);
                right.fork();
                return (left.join() + right.join());
            }

        }
    }
}
